const { history_list } = require("./data.js");
const { find_create_point, find_data_by_time } = require("./create.js");

const current_history_list = history_list;
const create_point = find_create_point();
console.log("create_point", create_point);

let total_info = {
  name: "动漫",
  total_fund: 8000,
  have: 0,
  have_fund: 0,
  income: 0,
  type: "",
};

const point = current_history_list.findIndex(
  (item) => item.create_time === create_point.create_time
);

const handle_nx = (height, month_min_rate) => {
  const range = Math.abs(height - month_min_rate);
  return `${Math.ceil(range / 5)}x`;
};

/**
 * 通用阶梯卖出计算函数
 * @param {number} initialAmount - 初始总量 (默认1)
 * @param {number} percent - 当前涨幅百分比
 * @param {number} nx - 触发卖出的涨幅步长
 * @returns {number} - 总卖出量
 */
const calculate_sale = (initialAmount, percent, nx, name) => {
  const increasePercent = parseFloat(percent);
  const stepPercent = nx.slice(0, -1);

  // 核心计算逻辑
  const fullStages = Math.floor(increasePercent / stepPercent);
  const fraction = increasePercent % stepPercent;

  // 阶梯卖出后剩余量，每次剩0.75，就是0.75的n次方
  const remainingAfterFull = initialAmount * Math.pow(0.75, fullStages);
  // 完整阶梯卖出量计算
  const fullStageSold = initialAmount - remainingAfterFull;

  // 未满阶梯的线性卖出量
  const fractionalRatio = fraction / stepPercent;
  const fractionalSold = remainingAfterFull * 0.25 * fractionalRatio;
  if (name === "华安") {
    return (fullStageSold + fractionalSold).toFixed(4);
  } else {
    return Math.ceil(fullStageSold + fractionalSold);
  }
};

const result_formatter = (obj) => {
  let info = obj;
  // if(){

  // }

  // return estimation > 0
  //   ? `${create_time} ${name}_${nx}: 卖出 ${result} 份`
  //   : `${create_time} ${name}_${nx}: 买入 ${Math.ceil(result)} 元`;
};

const submit = (obj) => {
  let {
    name,
    create_time,
    total_fund,
    have,
    have_fund,
    month_max_rate,
    month_min_rate,
    value,
    result,
  } = obj;
  const rest = total_fund - have_fund;
  const total = value > 0 ? have : rest;
  const current_estimation = parseFloat(value);
  const final_estimation = Math.abs(current_estimation);
  const nx = handle_nx(month_max_rate, month_min_rate);

  result = calculate_sale(total, final_estimation, nx, name);

  console.log(result_formatter({ nx, ...obj }));
};

for (let i = point; i <= current_history_list.length; i++) {
  let cur_data = {
    name: "动漫",
    total_fund: 8000,
    have: 0,
    have_fund: 0,
    result: 0,
    income: 0,
    ...create_point,
  };
  console.log("cur_data", cur_data);

  submit(cur_data);
}
